//
//  GCDTimer.swift
//  CommonWidgets
//
//  Created by sqkj on 2021/5/25.
//
import Foundation

public class GCDTimer: NSObject {
    
    public static var codeTimer: DispatchSourceTimer?

    public class func start(_ timeInterval: TimeInterval = 1,_ totolTimeInterval: TimeInterval = Double(MAXFLOAT), animation: @escaping (_ isFinish: Bool,_ count:TimeInterval,_ intTimeCount:TimeInterval )->()){
 
        var timeCount = totolTimeInterval
        
        var intTimeCount = 0
      
        GCDTimer.codeTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
 
        GCDTimer.codeTimer?.schedule(deadline: .now(), repeating: timeInterval)
        
        var isFinish = false
        
        GCDTimer.codeTimer?.setEventHandler(handler: {
            intTimeCount += 1
            timeCount = timeCount - timeInterval
          
            if timeCount == 0 {
                GCDTimer.codeTimer?.cancel()
                isFinish = true
            }
            
            DispatchQueue.main.async {
                animation(isFinish,timeCount,TimeInterval(intTimeCount))
            }
            
        })
        
        self.resume()
    }
    
    public class func resume() {
        GCDTimer.codeTimer?.resume()
    }
    
    public class func stop() {
        GCDTimer.codeTimer?.cancel()
    }

    
    /// GCD定时器倒计时
    ///
    /// - Parameters:
    ///   - timeInterval: 间隔时间
    ///   - repeatCount: 重复次数
    ///   - handler: 循环事件,闭包参数: 1.timer 2.剩余执行次数
    public class func dispatchTimer(timeInterval: Double, repeatCount: Int, handler: @escaping (DispatchSourceTimer?, Int) -> Void) ->DispatchSourceTimer?  {
        if repeatCount <= 0 {
            return nil
        }
        let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        var count = repeatCount
        timer.schedule(deadline: .now(), repeating: timeInterval)
        timer.setEventHandler {
            count -= 1
            DispatchQueue.main.async {
                handler(timer, count)
            }
            if count == 0 {
                timer.cancel()
            }
        }
        timer.resume()
        return timer
    }
    
    /// GCD定时器倒计时
    ///
    /// - Parameters:
    ///   - timeInterval: 间隔时间
    ///   - repeatCount: 重复次数
    ///   - handler: 循环事件,闭包参数: 1.timer 2.剩余执行次数
    public class func dispatch_timer(timeInterval: Double, repeatCount: Int, handler: @escaping (DispatchSourceTimer?, Int) -> Void){
        if repeatCount <= 0 {
            return
        }
        let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        var count = repeatCount
        timer.schedule(deadline: .now(), repeating: timeInterval)
        timer.setEventHandler {
            count -= 1
            DispatchQueue.main.async {
                handler(timer, count)
            }
            if count == 0 {
                timer.cancel()
            }
        }
        timer.resume()
    }
}
